Delete confirmation dialog in Blazor
Once a record is deleted from the database, there is no easy way to recover it. So it's always a good practice to display a confirmation on Delete. In this video we will discuss, how to implement delete confirmation in Blazor.
Reusable Blazor Confirmation Dialog Component
We will create a reusable confirmation dialog component so it can be used for displaying a confirmation dialog for any requirement, not just delete confirmation.
Confirmation Component Class (ConfirmBase.cs)
- We do not want to hard-code confirmation title and message.
- We want the calling component to be able to pass confirmation title and message.
- This makes this confirmation dialog component more reusable.
- This is the reason we created
ConfirmationTitle
andConfirmationMessage
properties. - To make this component even more reusable, we can create additional properties that can be used by the calling component to pass the display text for both DELETE and CANCEL buttons.
- The custom event
ConfirmationChanged
is fired everytime Delete or Cancel button is clicked. - The boolean property
ShowConfirmation
controls the visibility of the dialog on the UI.
Confirmation Component View (Confirm.razor)
- The view binds to
ConfirmationTitle
andConfirmationMessage
properties. The default values specified in the component class are used, if the calling component does not pass values explicitly. OnConfirmationChange
method in the component class is specified as the event handler for the following 3 buttons- Delete
- Cancel
- Close
- When Cancel and Close buttons are clicked, false is passed as the event payload (i.e event data). The calling component can subscribe to the custom event
ConfirmationChanged
and will have access to this event data. - When Delete button is clicked, true is passed as the event data.
- In the calling component, we can use the event data to determine if a confiramtion is given or not. True indicates confirmation given, false indicates confirmation not given.
Using Confirmation Dialog Component
In our example, Delete confirmation must be displayed when Delete button on Employee card is clicked.
@ref
attribute creates a reference to the component instance- The component reference (DeleteConfirmation) is used to call
Show()
method of the delete confirmation component which displays the dialog. ConfirmDelete_Click
is the event handler that handles the custom eventConfirmationChanged
.
© 2020 Pragimtech. All Rights Reserved.